<template>
  <div class="analysis-container">
    <!-- 顶部标题 -->
    <div class="header-section">
      <div class="title-area">
        <h1>
          <el-icon><Cpu /></el-icon>
          大模型数据分析
        </h1>
        <!-- <p class="subtitle">基于清洗数据的智能分析与可视化</p> -->
      </div>
    </div>

    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 左侧数据选择区域 -->
      <div class="left-section">
        <el-card shadow="never" class="data-card">
          <template #header>
            <div class="card-header">
              <h3>
                <el-icon><FolderOpened /></el-icon>
                选择清洗数据
              </h3>
            </div>
          </template>

          <el-table
            :data="cleanedDataList"
            highlight-current-row
            @current-change="handleDataSelect"
            style="width: 100%"
          >
            <el-table-column prop="file_id" label="清洗文件ID" width="150" />
            <el-table-column prop="clear_name" label="清洗名称" width="150" />
            <el-table-column prop="file_type" label="文件类型" width="100">
              <template #default="{ row }">
                <el-tag :type="getFileTypeTag(row.file_type)">
                  {{ row.file_type.toUpperCase() }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="counts" label="数据量" width="100" />
            <el-table-column prop="created_time" label="创建时间" min-width="150">
              <template #default="{ row }">
                {{ formatTime(row.created_time) }}
              </template>
            </el-table-column>
          </el-table>

          <div class="data-preview" v-if="selectedData">
            <div class="preview-header">
              <span>数据预览 (前5条)</span>
              <el-tag type="info">{{ selectedData.counts }} 条数据</el-tag>
            </div>
            <el-table :data="previewData" height="370" width="500" border>
              <el-table-column
                v-for="col in previewColumns"
                :key="col"
                :prop="col"
                :label="col"
                width="100"
              />
            </el-table>
          </div>
        </el-card>
      </div>

      <!-- 右侧分析区域 -->
      <div class="right-section">
        <el-card shadow="never" class="analysis-card">
          <template #header>
            <div class="card-header">
              <h3>
                <el-icon><Search /></el-icon>
                大模型分析
              </h3>
            </div>
          </template>

          <!-- 分析输入区域 -->
          <div class="analysis-input">
            <el-form :model="analysisForm" label-width="80px">
              <el-form-item label="分析问题">
                <el-input
                  v-model="analysisForm.question"
                  type="textarea"
                  :rows="3"
                  placeholder="向大模型提问，例如：分析用户性别分布情况、找出点赞数最高的内容类型等"
                  resize="none"
                />
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  @click="submitAnalysis"
                  :loading="analyzing"
                  :disabled="!selectedData"
                >
                  <el-icon><Promotion /></el-icon>
                  开始分析
                </el-button>
                <el-button @click="resetAnalysisForm">
                  <el-icon><Refresh /></el-icon>
                  重置
                </el-button>
              </el-form-item>
            </el-form>
          </div>

          <!-- 分析进度 -->
          <div v-if="analyzing" class="analysis-progress">
            <el-progress
              :percentage="progressPercent"
              :status="progressStatus"
              :text-inside="true"
              :stroke-width="20"
              striped
              striped-flow
            />
            <p class="progress-message">{{ progressMessage }}</p>
          </div>

          <!-- 分析结果展示 -->
          <div v-if="analysisResults.length > 0" class="analysis-results">
            <div class="results-header">
              <h4>分析历史记录</h4>
              <el-tag type="success">{{ analysisResults.length }} 次分析</el-tag>
            </div>

            <el-collapse v-model="activeResult" accordion>
              <el-collapse-item
                v-for="(result, index) in analysisResults"
                :key="result.Id"
                :name="result.Id"
                :class="{ 'current-result': index === 0 }"
              >
                <template #title>
                  <div class="result-title">
                    <el-icon><Document /></el-icon>
                    <span class="question">{{ result.questions }}</span>
                    <span class="time">{{ formatTime(result.created_time) }}</span>
                  </div>
                </template>
                <div class="result-content">
                  <div class="analysis-text">
                    <h5>分析结论：</h5>
                    <v-md-preview :text="result.contents"></v-md-preview>
                    <!-- <div class="content-box">{{ result.contents }}</div> -->
                  </div>
                  <div class="analysis-chart" v-if="result.results">
                    <h5>可视化图表：</h5>
                    <div class="chart-container">
                      <!-- 这里动态渲染图表 -->
                      <div v-html="generateGenderChart(result.results)"></div>
                    </div>
                  </div>
                  <div class="result-actions">
                    <el-button type="danger" size="small" @click.stop="deleteAnalysis(result.Id)">
                      <el-icon><Delete /></el-icon>
                      删除
                    </el-button>
                  </div>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>

          <!-- 空状态 -->
          <div v-else class="empty-analysis">
            <el-empty description="暂无分析记录，请选择数据并提问">
              <template #image>
                <el-icon :size="64"><DataAnalysis /></el-icon>
              </template>
            </el-empty>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import ClearoutAPI from "@/api/clearout";
import AnalyseAPI from "@/api/analyse";
import dayjs from "dayjs";
import * as echarts from "echarts";

// 模拟数据
const cleanedDataList: any = ref([]);
// 分析结果
const analysisResults: any = ref([]);
// 预览数据
const previewData = ref([]);
const previewColumns = ref([]);
const selectedData = ref(null);
function handleQuery() {
  ClearoutAPI.getPage()
    .then((data) => {
      cleanedDataList.value = data.list;
    })
    .finally();
  AnalyseAPI.getPage()
    .then((data) => {
      analysisResults.value = data.list;
    })
    .finally();
}
const generateGenderChart = (item) => {
  const chartId = "gender-chart-" + Math.random().toString(36).substr(2, 8);
  const chartHtml = `<div id="${chartId}" style="width:100%;height:300px;"></div>`;
  // 使用nextTick确保DOM更新后执行
  setTimeout(() => {
    const chartDom = document.getElementById(chartId);
    if (chartDom) {
      const myChart = echarts.init(chartDom);
      const option = JSON.parse(item);
      myChart.setOption(option);

      // 响应式调整
      window.addEventListener("resize", function () {
        myChart.resize();
      });
    }
  }, 100);

  return chartHtml;
};
// 分析表单
const analysisForm = reactive({
  question: "",
});

// 分析状态
const analyzing = ref(false);
const progressPercent = ref(0);
const progressStatus = ref("");
const progressMessage = ref("准备分析...");
const activeResult = ref(1);

// 获取文件类型标签样式
const getFileTypeTag = (type: string) => {
  switch (type) {
    case "csv":
      return "";
    case "excel":
      return "success";
    case "json":
      return "warning";
    case "database":
      return "danger";
    default:
      return "info";
  }
};

// 格式化时间
const formatTime = (time: string) => {
  return dayjs(time).format("YYYY-MM-DD HH:mm");
};

// 选择数据
const handleDataSelect = async (data: any) => {
  selectedData.value = data;
  // 模拟获取预览数据
  previewData.value = await AnalyseAPI.getData(data.file_id);
  previewColumns.value = Object.keys(previewData.value[0]);
};

// 提交分析
const submitAnalysis = () => {
  if (!analysisForm.question.trim()) {
    ElMessage.warning("请输入分析问题");
    return;
  }

  if (!selectedData.value) {
    ElMessage.warning("请选择要分析的数据");
    return;
  }

  analyzing.value = true;
  progressPercent.value = 0;
  progressStatus.value = "";
  progressMessage.value = "正在提交分析请求...";

  // 模拟分析过程
  const timer = setInterval(() => {
    progressPercent.value += Math.floor(Math.random() * 15) + 5;

    if (progressPercent.value < 30) {
      progressMessage.value = "正在解析问题...";
    } else if (progressPercent.value < 60) {
      progressMessage.value = "正在分析数据特征...";
    } else if (progressPercent.value < 90) {
      progressMessage.value = "正在生成分析结论...";
    } else {
      progressMessage.value = "正在准备可视化结果...";
    }
    if (progressPercent.value >= 100) {
      clearInterval(timer);
      setTimeout(() => {
        // completeAnalysis();
        AnalyseAPI.add({
          file_id: selectedData.value.file_id,
          questions: analysisForm.question,
        }).then(() => {
          ElMessage.success("分析完成");
          handleQuery();
          analyzing.value = false;
        });
      }, 500);
    }
  }, 500);
};

// 重置分析表单
const resetAnalysisForm = () => {
  analysisForm.question = "";
};

// 删除分析记录
const deleteAnalysis = (id: number) => {
  ElMessageBox.confirm("确定要删除此分析记录吗？", "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      AnalyseAPI.deleteByIds([record.id]);
      ElMessage.success("删除成功");
      handleQuery();
    })
    .catch(() => {});
};

onMounted(() => {
  handleQuery();
  // 默认选择第一个数据集
  if (cleanedDataList.value.length > 0) {
    handleDataSelect(cleanedDataList.value[0]);
  }
});
</script>

<style lang="scss" scoped>
.analysis-container {
  padding: 24px;
  background-color: #f8f9fa;
  // min-height: 100vh;
}

.header-section {
  margin-bottom: 24px;

  .title-area {
    h1 {
      margin: 0;
      font-size: 24px;
      font-weight: 600;
      color: #1f2d3d;
      display: flex;
      align-items: center;

      .el-icon {
        margin-right: 10px;
        font-size: 28px;
        color: #3a8ee6;
      }
    }

    .subtitle {
      margin: 4px 0 0;
      font-size: 14px;
      color: #8492a6;
    }
  }
}

.main-content {
  display: flex;
  gap: 20px;

  .left-section {
    flex: 0 0 400px;
  }

  .right-section {
    flex: 1;
  }
}

.data-card,
.analysis-card {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  height: 100%;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
      display: flex;
      align-items: center;

      .el-icon {
        margin-right: 8px;
        color: #3a8ee6;
      }
    }
  }
}

.data-preview {
  margin-top: 20px;
  border-top: 1px solid #f0f0f0;
  padding-top: 16px;

  .preview-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    font-weight: 500;
  }
}

.analysis-input {
  margin-bottom: 24px;
}

.analysis-progress {
  margin: 20px 0;

  .progress-message {
    margin-top: 8px;
    text-align: center;
    color: #606266;
    font-size: 13px;
  }
}

.analysis-results {
  .results-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid #f0f0f0;

    h4 {
      margin: 0;
      font-size: 15px;
      font-weight: 600;
    }
  }

  .result-title {
    display: flex;
    align-items: center;
    width: 100%;

    .el-icon {
      margin-right: 8px;
      color: #3a8ee6;
    }

    .question {
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      margin-right: 12px;
    }

    .time {
      color: #909399;
      font-size: 12px;
    }
  }

  .result-content {
    padding: 16px;

    .analysis-text {
      margin-bottom: 20px;

      h5 {
        margin: 0 0 8px 0;
        font-size: 14px;
        font-weight: 600;
      }

      .content-box {
        padding: 12px;
        background-color: #f8f9fa;
        border-radius: 4px;
        line-height: 1.6;
        white-space: pre-wrap;
      }
    }

    .analysis-chart {
      h5 {
        margin: 0 0 8px 0;
        font-size: 14px;
        font-weight: 600;
      }

      .chart-container {
        border: 1px solid #f0f0f0;
        border-radius: 4px;
        padding: 10px;
      }
    }

    .result-actions {
      display: flex;
      justify-content: flex-end;
      margin-top: 16px;
      padding-top: 16px;
      border-top: 1px solid #f0f0f0;
    }
  }

  .current-result {
    :deep(.el-collapse-item__header) {
      background-color: #f0f7ff;
    }
  }
}

.empty-analysis {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;

  .el-icon {
    color: var(--el-color-primary);
  }
}

@media (max-width: 1200px) {
  .main-content {
    flex-direction: column;

    .left-section,
    .right-section {
      flex: 1 1 auto;
    }
  }
}
</style>
